﻿Namespace EIBData.DPT
    Public MustInherit Class EIBDataDPT_24_Base
        Inherits EIBDataDPT_Base

        Protected _value As String = Nothing


        Sub New(data As Byte())
            If Not CanEncode(data) Then Throw New EIB.Exceptions.EIBDataDecodeException("")
            If Not data(data.Length - 1) = 0 Then Throw New EIB.Exceptions.EIBDataDecodeException("") 'String must be 0x00 terminated

            MyBase._data = data

            Dim valueBase As Byte() = New Byte(data.Length - 3) {} 'auto-remove last 0x00
            For i = 0 To data.Length - 3
                valueBase(i) = data(i + 1)
            Next
            _value = System.Text.Encoding.UTF8.GetChars(valueBase)
        End Sub

        Sub New(value As String)
            _value = value

            Dim valueArr As Byte() = System.Text.Encoding.UTF8.GetBytes(value)
            Dim valueBase As Byte() = New Byte(valueArr.Length + 1) {}
            Array.Copy(valueArr, 0, valueBase, 1, valueArr.Length)
            valueBase(0) = 0 'first 
            valueBase(valueBase.Length - 1) = 0 '0x00 terminated

            MyBase._data = valueBase
        End Sub


        Public Overrides Function CanEncode(data() As Byte) As Boolean
            Return data IsNot Nothing AndAlso data.Length > 1 '= DPT_OctetLength
        End Function

        Public Overrides Function ToString() As String
            Return _value
        End Function

        Public Overrides Function ToObject() As Object()
            Return New Object() {_value}
        End Function

        Public Overrides ReadOnly Property ObjectType As System.Type()
            Get
                Return New Type() {GetType(String)}
            End Get
        End Property

        Public Overrides Function ToInfoList() As List(Of EIB.InfoBase)
            Dim list As New List(Of EIB.InfoBase)

            list.Add(New EIB.Info("Type", DPT_Name))
            list.Add(New EIB.Info("String", _value))

            Return list
        End Function

        Public Shared Shadows ReadOnly Property DPT_BaseName As String
            Get
                Return "A[n]"
            End Get
        End Property

        Public Shared Shadows ReadOnly Property DPT_OctetLength As Byte
            Get
                Return 255
            End Get
        End Property

        Public Shared Shadows ReadOnly Property DPT_Name As String
            Get
                Return "DPT_24"
            End Get
        End Property

        Public Shared Shadows ReadOnly Property DPT_Number As String
            Get
                Return "24.xxx"
            End Get
        End Property

        Public ReadOnly Property Value As String
            Get
                Return _value
            End Get
        End Property
    End Class
End Namespace